/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rapidp2p.backend;

/**
 *
 * @author LF
 */
import java.io.*;
import java.net.*;

public class UDPClient {

    String fileList;
    String searchSentence;

    UDPClient() {
        fileList = "";
    }

    public String uploadFileList() {

        String currentDirectory = System.getProperty("user.home");
        File uploadDirectory = new File(currentDirectory + "\\share\\");
        System.out.println("Client Home Directory:");
        System.out.println(uploadDirectory);


        // if the directory does not exist, create it
        if (!uploadDirectory.exists()) {
            System.out.println("creating directory: share");
            uploadDirectory.mkdir();
        }
        //try {
        // Directory path here
        String path = uploadDirectory.toString();

        String files;
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {//prints list of files on Client

            if (listOfFiles[i].isFile()) {
                files = listOfFiles[i].getName();
                System.out.println("\t" + files);
            }
        }

        for (int req = 0; req < listOfFiles.length; req++) {
            fileList += listOfFiles[req].toString() + "," + listOfFiles[req].length() + "\n";
        }

        return fileList;
    }

    public void beginClient() {

        TCPClient tcpclient;
        RequestFile rFile;
        DirectoryEntry [] resultEntries = new DirectoryEntry[100];
        DatagramSocket clientSocket = null;
        InetAddress IPAddress = null;
        InetAddress tempIP = null;
        String nextMessage = null;
        BufferedReader inFromUser =
                new BufferedReader(new InputStreamReader(System.in));
        try {
            clientSocket = new DatagramSocket();
        } catch (SocketException se) {
            System.out.println("clientSocket UDPClient problem\n");
        }
        try {
            IPAddress = InetAddress.getByName("localhost");
        } catch (UnknownHostException uhe) {
            System.out.println("UnknownHostException\n");
        }
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];


        //take user IP input (which is server ip)
        try {
            tempIP = InetAddress.getByName("10.5.1.40");
        } catch (UnknownHostException uhe) {
        }


        //String sentence = uploadFileList(fileList);
        sendData = fileList.getBytes();//file list to be sent
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, tempIP, 9876);//change IP address
        try {
            clientSocket.send(sendPacket);
        } catch (IOException io) {
            System.out.println("clientSocket sendPacket UDPClient problem\n");
            System.exit(-1);
        }
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        try {
            clientSocket.receive(receivePacket);
        } catch (IOException io) {
            System.out.println("clientSocket receivePacket UDPClient problem\n");
            System.exit(-1);
        }
        String modifiedSentence = new String(receivePacket.getData());
        System.out.println("FROM SERVER:\n" + modifiedSentence);

        boolean isRunning = true;
        //constant user inputs in this loop, also initiate transfer here based on command
        //start tcp server to listen for clients
        //TCPServer tcpServer = new TCPServer();
        //tcpServer.listenSocket();
        while (isRunning) {
            System.out.println("is running");
            //BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
            try {
                System.out.println("Next command");
                nextMessage = inFromUser.readLine();
                System.out.println(nextMessage);
            } catch (IOException io) {
                System.out.println("user input problem UDPClient\n");
            }
            nextMessage += "\n";
//            if (nextMessage.equals("close")) {
//                //return;
//            }

            if (nextMessage.contains("download")) {
                String [] downloadIndex = nextMessage.split(",");
                int downloadPointer = Integer.parseInt(downloadIndex[1].substring(0, 1));
                String saveName = shortFileName(resultEntries[downloadPointer].getFilename());//name used to create file upon download
                System.out.println("save name is " + resultEntries[downloadPointer].getFilename());
                System.out.println("nextMesssage or command is now download\n");
                
              //  tcpclient = new TCPClient("192.168.0.102");
              //  tcpclient.tcpClientInit(saveName);
                rFile = new RequestFile(resultEntries[downloadPointer].getFilename());
                rFile.requestFile("10.5.1.40");
                rFile.download();
            }

            sendData = new byte[2048];
            receiveData = new byte[2048];
            sendData = nextMessage.getBytes();
            DatagramPacket sendPacket2 = new DatagramPacket(sendData, sendData.length, tempIP, 9876);
            try {
                clientSocket.send(sendPacket2);
            } catch (IOException io) {
                System.out.println("sendPacket2 clientSocket UDPClient problem\n");
            }
            //byte [] receiveData2 = new byte[2048];
            DatagramPacket receivePacket2 = new DatagramPacket(receiveData, receiveData.length, tempIP, 9876);
            try {
                clientSocket.receive(receivePacket2);
            } catch (IOException io) {
                System.out.println("clientSocket receivePacket2 UDPClient problem\n");
            }
            searchSentence = new String(receivePacket2.getData());
            //InetAddress ip = null;
            String[] lines = searchSentence.split("\n");   //split RESULTS into [] of lines
            //each line represents single file search results
            for (int i = 0; i < lines.length - 1; i++) {              //TEST: print LINES[]
                System.out.println("Search Result " + i + "\t" + lines[i] + "\n");
            }

            String[] entryFields = new String[3];      //array to store field of each line - 3 fields of mp3 entry                               
            //String searchResults = "";

            for (int k = 0; k < lines.length - 1; k++) {
                InetAddress ip = null;
                entryFields = lines[k].split(",");
                System.out.println("Result Line's length : " + (lines.length - 1));
                System.out.println("IP of file is " + entryFields[2]);
                //String newip = entryFields[2];
//                try{
//                ip = InetAddress.getByName(newip);
//                
//                } catch (UnknownHostException e){
//                    System.out.println("Can't convert ip from String\n");
//                }
                resultEntries[k] = new DirectoryEntry(entryFields[0], entryFields[1], entryFields[2]);
            }
            
            System.out.println(resultEntries.toString());
            System.out.println("Result Array formed\n");
            System.out.println("Search Results:\n" + searchSentence);
            System.out.println("resultEntries length" + resultEntries.length);
            for(int k=0; k<resultEntries.length-1;k++){
                if(resultEntries[k] !=null)
                System.out.println("Index " + k + " " + resultEntries[k].getFilename() + 
                                    " " + resultEntries[k].getFileSize() + " " + resultEntries[k].getHostname());
            }

        }
        clientSocket.close();
    }
    
    //this method takes a full path of file on server, extracts just the filename
    //needed for TCPClient to create a file with that name in share folder or the download destination
    public String shortFileName(String fullPath){
        String shortName = new File(fullPath).getName();
        return shortName;
    }

    public static void main(String args[]) throws Exception {
        UDPClient udpClient = new UDPClient();
        udpClient.uploadFileList();
        udpClient.beginClient();


    }
}
